// Flashcard variables
const card = document.getElementById('flashcard');
const cardFront = document.getElementById('cardFront');
const cardBack = document.getElementById('cardBack');
const explanationContent = document.getElementById('explanationContent');
const spellingTestSection = document.getElementById('spellingTestSection');
const spellingInput = document.getElementById('spellingInput');
const checkSpellingButton = document.getElementById('checkSpellingButton');
const spellingFeedback = document.getElementById('spellingFeedback');
const prevButton = document.getElementById('prevButton');
const nextButton = document.getElementById('nextButton');
const fileInput = document.getElementById('fileInput');
const fileNameDisplay = document.getElementById('fileNameDisplay');
const progressDisplay = document.getElementById('progressDisplay');
const wrongQuestionsListContainer = document.getElementById('wrongQuestionsListContainer'); // Added
const wrongQuestionsList = document.getElementById('wrongQuestionsList'); // Added
const searchTermInput = document.getElementById('searchTermInput'); // Added
const searchResultsContainer = document.getElementById('searchResultsContainer'); // Added
const clearSearchButton = document.getElementById('clearSearchButton'); // Added
const sendFrontToAiButton = document.getElementById('sendFrontToAiButton');
const sendBackToAiButton = document.getElementById('sendBackToAiButton');

let termsData = [];
let currentCardIndex = 0;
let wronglyAnsweredIndices = []; // Added

// AI Chat variables
// const apiKeyInput = document.getElementById('apiKeyInput'); // Removed
// const saveApiKeyButton = document.getElementById('saveApiKeyButton'); // Removed
const chatHistory = document.getElementById('chatHistory');
const chatInput = document.getElementById('chatInput');
const sendChatButton = document.getElementById('sendChatButton');

// Get AI Preset Action Buttons
const generateExampleButton = document.getElementById('generateExampleButton');
const synonymAntonymButton = document.getElementById('synonymAntonymButton');
const detailedDefinitionButton = document.getElementById('detailedDefinitionButton');
const relatedKnowledgeButton = document.getElementById('relatedKnowledgeButton');

// Add event listeners for AI Preset Action Buttons
if (generateExampleButton) {
    generateExampleButton.addEventListener('click', () => {
        if (termsData.length > 0 && termsData[currentCardIndex]) {
            const term = termsData[currentCardIndex].term;
            // 构建发送给AI的提示语
            chatInput.value = `请为术语 "${term}" 生成一个例句。`;
            sendChatMessage(); // 调用发送消息函数
        } else {
            alert('请先加载闪卡数据。');
        }
    });
}

if (synonymAntonymButton) {
    synonymAntonymButton.addEventListener('click', () => {
        if (termsData.length > 0 && termsData[currentCardIndex]) {
            const term = termsData[currentCardIndex].term;
            chatInput.value = `请为术语 "${term}" 提供同义词和反义词。`;
            sendChatMessage();
        } else {
            alert('请先加载闪卡数据。');
        }
    });
}

if (detailedDefinitionButton) {
    detailedDefinitionButton.addEventListener('click', () => {
        if (termsData.length > 0 && termsData[currentCardIndex]) {
            const term = termsData[currentCardIndex].term;
            const explanation = termsData[currentCardIndex].explanation || ''; // 获取解释，可能为空
            chatInput.value = `请详细解释术语 "${term}"${explanation ? '。原有解释：' + explanation : ''}。`; // 可以包含原有解释作为上下文
            sendChatMessage();
        } else {
            alert('请先加载闪卡数据。');
        }
    });
}

if (relatedKnowledgeButton) {
    relatedKnowledgeButton.addEventListener('click', () => {
        if (termsData.length > 0 && termsData[currentCardIndex]) {
            const term = termsData[currentCardIndex].term;
             const explanation = termsData[currentCardIndex].explanation || '';
            chatInput.value = `请提供与术语 "${term}"${explanation ? ' (解释: ' + explanation + ')' : ''} 相关的背景知识或引申概念。`;
            sendChatMessage();
        } else {
            alert('请先加载闪卡数据。');
        }
    });
}

let userApiKey = ''; // Please set your API key here
let isWaitingForAIResponse = false; // Flag to track AI response status

const MAX_CHAT_HISTORY = 5; // Store user + AI as one entry for simplicity here, so 5 pairs
let conversationHistory = []; // Stores {role: 'user'/'assistant', content: '...'} objects

const SYSTEM_PROMPT = "You are a helpful English teacher. You are excellent at answering questions, especially for translating complex terms or explaining them with similar sentences and examples. When asked about a term, provide a concise translation if applicable, and then explain it clearly, perhaps using an analogy or a simpler sentence structure.Do not reply in markdown format.";

// --- Flashcard Logic ---
function loadSavedState() {
    const savedFileName = localStorage.getItem('flashcards_lastFileName');
    const savedFileContent = localStorage.getItem('flashcards_lastFileContent');
    const savedCardIndex = localStorage.getItem('flashcards_lastCardIndex');

    if (savedFileContent && savedFileName) {
        fileNameDisplay.textContent = `已恢复: ${savedFileName}`;
        try {
            termsData = JSON.parse(savedFileContent);
            if (Array.isArray(termsData) && termsData.length > 0) {
                currentCardIndex = parseInt(savedCardIndex, 10) || 0;
                if (currentCardIndex >= termsData.length || currentCardIndex < 0) {
                    currentCardIndex = 0;
                }
                // Load wrong questions
                const savedWrongIndices = localStorage.getItem('flashcards_wrongIndices_' + savedFileName); // File-specific
                if (savedWrongIndices) {
                    wronglyAnsweredIndices = JSON.parse(savedWrongIndices);
                } else {
                    wronglyAnsweredIndices = [];
                }
                displayCard();
                updateButtonStates();
                updateWrongQuestionsDisplay(); // Added
            } else {
                alert('之前保存的JSON数据无效或为空，已清除。');
                resetState(); // resetState will clear wrong questions too
            }
        } catch (error) {
            alert('恢复保存的数据时出错: ' + error.message + ' 已清除之前保存的数据。');
            resetState(); // resetState will clear wrong questions too
        }
    } else {
        updateButtonStates();
        updateWrongQuestionsDisplay(); // Ensure it's updated (e.g. to show "no items")
    }
}

fileInput.addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            try {
                const parsedData = JSON.parse(e.target.result);
                if (Array.isArray(parsedData) && parsedData.length > 0) {
                    termsData = parsedData;
                    currentCardIndex = 0;
                    fileNameDisplay.textContent = `已选择文件: ${file.name}`;
                    localStorage.setItem('flashcards_lastFileName', file.name);
                    localStorage.setItem('flashcards_lastFileContent', e.target.result);

                    // Reset wrong questions list for the new file
                    wronglyAnsweredIndices = [];
                    localStorage.removeItem('flashcards_wrongIndices_' + file.name); // File-specific
                    updateWrongQuestionsDisplay(); // Added
                    clearSearchResults(); // Added: Clear search on new file

                    displayCard();
                    updateButtonStates();
                } else {
                    alert('JSON 文件格式无效或为空。');
                    resetState();
                }
            } catch (error) {
                alert('读取或解析JSON文件时出错: ' + error.message);
                resetState();
            }
        };
        reader.onerror = function() {
            alert('读取文件失败。');
            resetState();
        };
        reader.readAsText(file);
    } else {
        if (termsData.length === 0) {
            fileNameDisplay.textContent = '请选择一个 JSON 文件';
            cardFront.textContent = '请选择文件并开始';
            cardBack.textContent = '解释会在这里';
            progressDisplay.textContent = '';
            updateButtonStates();
        }
    }
});

card.addEventListener('click', () => {
    if (termsData.length > 0) {
        card.classList.toggle('flipped');
    }
});

nextButton.addEventListener('click', () => {
    if (currentCardIndex < termsData.length - 1) {
        currentCardIndex++;
        displayCard();
        updateButtonStates();
        clearSearchResults(); // Added: Clear search on navigation
    }
});

prevButton.addEventListener('click', () => {
    if (currentCardIndex > 0) {
        currentCardIndex--;
        displayCard();
        updateButtonStates();
        clearSearchResults(); // Added: Clear search on navigation
    }
});

function displayCard() {
    if (termsData.length === 0) {
         cardFront.textContent = '请选择文件并开始';
         explanationContent.textContent = '解释会在这里';
         spellingTestSection.style.display = 'none';
         progressDisplay.textContent = '';
         return;
    }
    const currentTerm = termsData[currentCardIndex];
    cardFront.textContent = currentTerm.term;
    explanationContent.textContent = currentTerm.explanation || '（无解释）';

    spellingInput.value = '';
    spellingFeedback.textContent = '';
    checkSpellingButton.disabled = false;
    checkSpellingButton.textContent = '检查';
    spellingTestSection.style.display = 'block';

    card.classList.remove('flipped');
    progressDisplay.textContent = `卡片 ${currentCardIndex + 1} / ${termsData.length}`;
    if (localStorage.getItem('flashcards_lastFileContent')) {
         localStorage.setItem('flashcards_lastCardIndex', currentCardIndex.toString());
    }
    sendFrontToAiButton.style.display = 'block';
    sendBackToAiButton.style.display = 'block';
}

function updateButtonStates() {
    prevButton.disabled = currentCardIndex === 0 || termsData.length === 0;
    nextButton.disabled = currentCardIndex === termsData.length - 1 || termsData.length === 0;
    const noData = termsData.length === 0;
    sendFrontToAiButton.style.display = noData ? 'none' : 'block';
    sendBackToAiButton.style.display = noData ? 'none' : 'block';
    if (spellingTestSection) {
        spellingTestSection.style.display = noData ? 'none' : 'block';
    }
}

function resetState(){
    termsData = [];
    currentCardIndex = 0;
    cardFront.textContent = '请选择文件并开始';
    explanationContent.textContent = '解释会在这里';
    spellingTestSection.style.display = 'none';
    spellingInput.value = '';
    spellingFeedback.textContent = '';
    card.classList.remove('flipped');
    progressDisplay.textContent = '';
    fileNameDisplay.textContent = '请选择一个 JSON 文件';
    localStorage.removeItem('flashcards_lastFileName');
    localStorage.removeItem('flashcards_lastFileContent');
    localStorage.removeItem('flashcards_lastCardIndex');

    // Clear wrong questions for the current file (if a file was loaded)
    const lastFileName = localStorage.getItem('flashcards_lastFileName'); // Get it before removing
    if (lastFileName) { // Check if a filename was actually stored to make it specific
         localStorage.removeItem('flashcards_wrongIndices_' + lastFileName);
    } else { // Fallback if no specific filename, though less ideal
         localStorage.removeItem('flashcards_wrongIndices');
    }
    wronglyAnsweredIndices = []; // Added
    updateWrongQuestionsDisplay(); // Added
    clearSearchResults(); // Added: Clear search on reset

    updateButtonStates();
    sendFrontToAiButton.style.display = 'none';
    sendBackToAiButton.style.display = 'none';
}

// Prevent card flip when clicking on the spelling test area
if (spellingTestSection) {
    spellingTestSection.addEventListener('click', (event) => {
        event.stopPropagation();
    });
}

// --- AI Chat Logic ---
sendFrontToAiButton.addEventListener('click', (e) => {
    e.stopPropagation(); // Prevent card flip
    if (termsData.length > 0 && termsData[currentCardIndex]) {
        const term = termsData[currentCardIndex].term;
        chatInput.value = `翻译 ${term}`;
        chatInput.focus();
    }
});

sendBackToAiButton.addEventListener('click', (e) => {
    e.stopPropagation(); // Prevent card flip
    if (termsData.length > 0 && termsData[currentCardIndex]) {
        const explanation = termsData[currentCardIndex].explanation;
        if (explanation) {
            chatInput.value = `翻译 ${explanation}`;
            chatInput.focus();
        } else {
            alert('当前卡片背面没有解释内容。');
        }
    }
});

sendChatButton.addEventListener('click', sendChatMessage);
chatInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        sendChatMessage();
    }
});

function addMessageToChatHistory(role, content) {
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('chat-message');
    // Use 'assistant' for AI messages in the display class as well for consistency, though it's mainly for API
    messageDiv.classList.add(role === 'user' ? 'user-message' : (role === 'assistant' ? 'ai-message' : 'ai-message')); // Keep 'ai-message' for CSS if preferred
    messageDiv.textContent = content;
    chatHistory.appendChild(messageDiv);
    chatHistory.scrollTop = chatHistory.scrollHeight; // Scroll to bottom

    // Add to conversation history array for API call
    // Ensure the role here is one of 'system', 'user', or 'assistant'
    conversationHistory.push({ role, content });
    if (conversationHistory.length > MAX_CHAT_HISTORY * 2) { // Each turn is user + AI
        conversationHistory.splice(0, conversationHistory.length - (MAX_CHAT_HISTORY * 2) +1 ); // Keep last 5 pairs + current user message
    }
}

async function sendChatMessage() {
    const messageText = chatInput.value.trim();
    if (!messageText) return;
    if (isWaitingForAIResponse) {
        alert('请等待上一条消息回复后再发送新消息。');
        return;
    }

    addMessageToChatHistory('user', messageText);
    chatInput.value = '';
    isWaitingForAIResponse = true;
    chatInput.disabled = true;
    sendChatButton.disabled = true;

    // Add placeholder with 'assistant' role for internal tracking, but display as 'ai-message'
    const thinkingDiv = document.createElement('div');
    thinkingDiv.classList.add('chat-message', 'ai-message');
    thinkingDiv.textContent = '思考中...';
    chatHistory.appendChild(thinkingDiv);
    chatHistory.scrollTop = chatHistory.scrollHeight;
    // Add a temporary 'assistant' message to conversationHistory for the placeholder
    conversationHistory.push({ role: 'assistant', content: '思考中...' });

    // Prepare messages for API: system prompt + relevant conversation history
    // Ensure conversationHistory only contains valid roles ('system', 'user', 'assistant')
    const messagesForApi = conversationHistory.filter(msg => ['system', 'user', 'assistant'].includes(msg.role));

    const messagesPayload = [
        { role: "system", content: SYSTEM_PROMPT },
        // Take the last (MAX_CHAT_HISTORY * 2 -1) from filtered history to make space for current user message
        // The current user message is already in messagesForApi. The placeholder 'assistant' message is also there.
        ...messagesForApi.slice(-(MAX_CHAT_HISTORY * 2))
    ];

    try {
        const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${userApiKey}`,
                'Content-Type': 'application/json',
                'Accept': 'application/json' // Added for good measure
            },
            body: JSON.stringify({
                model: 'deepseek-ai/DeepSeek-V3', // Changed model as per user request, ensure this model is available
                messages: messagesPayload,
                stream: false,
                max_tokens: 512,
                enable_thinking: false,
                temperature: 0.7,
                top_p: 0.7,
                // min_p: 0.05, // Optional params, can be added if needed
                // stop: null,
                // top_k: 50,
                // frequency_penalty: 0.5,
                // enable_thinking: false, // These seem specific, ensure API supports them
                // thinking_budget: 4096,
            })
        });

        // Remove the '思考中...' placeholder
        const thinkingMessage = chatHistory.querySelector('.ai-message:last-child');
        if (thinkingMessage && thinkingMessage.textContent === '思考中...') {
            thinkingMessage.remove();
            conversationHistory.pop(); // Remove the placeholder from conversation history as well
        }
        isWaitingForAIResponse = false;
        chatInput.disabled = false;
        sendChatButton.disabled = false;

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: response.statusText }));
            console.error('API Error Response:', errorData);
            addMessageToChatHistory('ai', `错误: ${errorData.error ? errorData.error.message : (errorData.message || '无法获取AI回复')}`);
            return;
        }

        const data = await response.json();
        if (data.choices && data.choices.length > 0 && data.choices[0].message) {
            const aiResponse = data.choices[0].message.content;
            addMessageToChatHistory('assistant', aiResponse); // API uses 'assistant' role, this is correct
        } else {
            addMessageToChatHistory('assistant', '未能从AI获取有效回复。'); // Use 'assistant' for consistency
        }

    } catch (error) {
        console.error('Error sending message to AI:', error);
         // Ensure placeholder is removed on network error too
        if (thinkingDiv.parentNode === chatHistory) {
            chatHistory.removeChild(thinkingDiv);
        }
        if (conversationHistory.length > 0 && conversationHistory[conversationHistory.length - 1].content === '思考中...') {
            conversationHistory.pop();
        }
        addMessageToChatHistory('assistant', '与AI通信时发生错误: ' + error.message); // Use 'assistant'
        isWaitingForAIResponse = false;
        chatInput.disabled = false;
        sendChatButton.disabled = false;
    }
}

// Add event listener for the check spelling button
if (checkSpellingButton) {
    checkSpellingButton.addEventListener('click', (e) => {
        e.stopPropagation(); // Added to prevent card flip
        if (termsData.length === 0) return;

        const userInput = spellingInput.value.trim();
        const correctTerm = termsData[currentCardIndex].term;

        if (userInput.toLowerCase() === correctTerm.toLowerCase()) {
            spellingFeedback.textContent = '正确!';
            spellingFeedback.style.color = 'green';
            checkSpellingButton.disabled = true;
            checkSpellingButton.textContent = '已掌握';

            // Remove from wrong list if it was there
            const indexInWrongList = wronglyAnsweredIndices.indexOf(currentCardIndex);
            if (indexInWrongList > -1) {
                wronglyAnsweredIndices.splice(indexInWrongList, 1);
                const currentFileName = localStorage.getItem('flashcards_lastFileName');
                if (currentFileName) {
                    localStorage.setItem('flashcards_wrongIndices_' + currentFileName, JSON.stringify(wronglyAnsweredIndices));
                }
                updateWrongQuestionsDisplay();
            }
        } else {
            spellingFeedback.textContent = `错误。正确答案: ${correctTerm}`;
            spellingFeedback.style.color = 'red';

            // Add to wrong list if not already there
            if (!wronglyAnsweredIndices.includes(currentCardIndex)) {
                wronglyAnsweredIndices.push(currentCardIndex);
                wronglyAnsweredIndices.sort((a, b) => a - b); // Keep sorted
                const currentFileName = localStorage.getItem('flashcards_lastFileName');
                if (currentFileName) {
                     localStorage.setItem('flashcards_wrongIndices_' + currentFileName, JSON.stringify(wronglyAnsweredIndices));
                }
                updateWrongQuestionsDisplay();
            }
        }
    });
}

// --- Initialization ---
document.addEventListener('DOMContentLoaded', () => {
    loadSavedState(); // Load flashcard state
    // AI chat is ready, user needs to input API key
    // if (!userApiKey) { // Removed, key is hardcoded
        // For initial message, we can use 'assistant' role for internal history, but display as 'ai-message'
    const initialAiMsgDiv = document.createElement('div');
    initialAiMsgDiv.classList.add('chat-message', 'ai-message');
    initialAiMsgDiv.textContent = '欢迎使用AI助手！直接开始提问吧。'; // Updated welcome message
    chatHistory.appendChild(initialAiMsgDiv);
        // No need to add this to conversationHistory as it's not part of an actual conversation turn for the API yet.
    // }
    // Initialize spelling section visibility & wrong questions list
    if (termsData.length === 0 && spellingTestSection) { // Ensure spellingTestSection exists
         spellingTestSection.style.display = (termsData.length === 0) ? 'none' : 'block';
    }
    updateWrongQuestionsDisplay(); // Call on initial load as well
    clearSearchResults(); // Ensure search is clear on load
});

function updateWrongQuestionsDisplay() {
    if (!wrongQuestionsList || !wrongQuestionsListContainer) return;

    wrongQuestionsList.innerHTML = ''; // Clear previous items

    if (termsData.length === 0 || wronglyAnsweredIndices.length === 0) {
        const noItemsMsg = document.createElement('li');
        noItemsMsg.textContent = '暂无错题记录';
        noItemsMsg.className = 'no-wrong-questions'; // Added class for styling
        wrongQuestionsList.appendChild(noItemsMsg);
        // wrongQuestionsListContainer.style.display = termsData.length === 0 ? 'none' : 'block'; // Hide if no terms data
        return;
    }

    // wrongQuestionsListContainer.style.display = 'block'; // Ensure it's visible

    wronglyAnsweredIndices.forEach(index => {
        if (index >= 0 && index < termsData.length) {
            const termItem = termsData[index];
            const listItem = document.createElement('li');
            listItem.textContent = `第 ${index + 1} 题: ${termItem.term.substring(0, 25)}${termItem.term.length > 25 ? '...' : ''}`;
            listItem.setAttribute('data-card-index', index);

            listItem.addEventListener('click', function() {
                const cardIdx = parseInt(this.getAttribute('data-card-index'), 10);
                if (!isNaN(cardIdx)) {
                    currentCardIndex = cardIdx;
                    displayCard();
                    card.classList.add('flipped');
                    // Scroll to the card (optional, can be jumpy)
                    // document.querySelector('.card-container').scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            });
            wrongQuestionsList.appendChild(listItem);
        }
    });
}

// --- Search Logic ---
function clearSearchResults() {
    if (searchTermInput) searchTermInput.value = '';
    if (searchResultsContainer) {
        searchResultsContainer.innerHTML = '';
        searchResultsContainer.style.display = 'none';
    }
}

if (searchTermInput && searchResultsContainer && clearSearchButton) {
    searchTermInput.addEventListener('input', function() {
        const query = this.value.trim().toLowerCase();
        searchResultsContainer.innerHTML = '';

        if (query.length < 1 || termsData.length === 0) { // Require at least 1 char for search
            searchResultsContainer.style.display = 'none';
            return;
        }

        const matchedTerms = termsData.reduce((acc, termData, index) => {
            if (termData.term.toLowerCase().includes(query)) {
                acc.push({ term: termData.term, originalIndex: index });
            }
            return acc;
        }, []).slice(0, 10); // Limit to 10 results

        if (matchedTerms.length > 0) {
            matchedTerms.forEach(item => {
                const div = document.createElement('div');
                div.classList.add('search-result-item');
                div.textContent = item.term;
                div.setAttribute('data-index', item.originalIndex);
                div.addEventListener('click', function() {
                    currentCardIndex = parseInt(this.getAttribute('data-index'), 10);
                    displayCard();
                    card.classList.remove('flipped'); // Ensure card is on the front
                    clearSearchResults();
                });
                searchResultsContainer.appendChild(div);
            });
            searchResultsContainer.style.display = 'block';
        } else {
            const noResultsDiv = document.createElement('div');
            noResultsDiv.classList.add('search-no-results');
            noResultsDiv.textContent = '未找到匹配项';
            searchResultsContainer.appendChild(noResultsDiv);
            searchResultsContainer.style.display = 'block';
        }
    });

    clearSearchButton.addEventListener('click', clearSearchResults);

    // Optional: Hide results if clicked outside
    document.addEventListener('click', function(event) {
        const isClickInsideSearch = searchTermContainer.contains(event.target) || searchResultsContainer.contains(event.target);
        if (!isClickInsideSearch) {
            searchResultsContainer.style.display = 'none';
        }
    });
}
